package py.com.fms.com.session.transactions;

//External classes imports 
//Java Classes
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.richfaces.component.html.HtmlDatascroller;

import com.ibatis.sqlmap.client.SqlMapClient;

import javax.faces.application.FacesMessage;
import javax.faces.validator.ValidatorException;

//project classes imports
import py.com.fms.com.bean.MethodOfPaymentBean;
import py.com.fms.com.bean.OrderHeadBean;
import py.com.fms.com.bean.PaymentOrderDetBean;
import py.com.fms.com.bean.PaymentOrderHeadBean;
import py.com.fms.com.bean.PurchasesDetBean;
import py.com.fms.com.bean.PurchasesHeadBean;
import py.com.fms.com.bean.SupplyCostStockBean;
import py.com.fms.com.persistence.services.MethodOfPaymentServices;
import py.com.fms.com.persistence.services.PaymentOrderServices;
import py.com.fms.com.persistence.services.PurchasesServices;
import py.com.fms.com.persistence.services.SupplyCostStockServices;
import py.com.fms.exception.CommonException;
import py.com.fms.fms.bean.BankAccountsBean;
import py.com.fms.fms.bean.TypeOfPayAndCollectionDetBean;
import py.com.fms.fms.bean.TypeOfPayAndCollectionHeadBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.bean.VoucherBean;
import py.com.fms.fms.persistence.services.BankAccountsServices;
import py.com.fms.fms.persistence.services.CurrencyServices;
import py.com.fms.fms.persistence.services.QuotationServices;
import py.com.fms.fms.persistence.services.TypeOfPayAndCollectionServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.fms.persistence.services.VoucherServices;
import py.com.fms.fms.session.maintenances.EditNumbers;
import py.com.fms.session.ComAssistant;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.session.modalSelectHolder;
import py.com.fms.utilities.ConvertAssistant;
import py.com.fms.utilities.DateAssistant;


@SuppressWarnings("unused")
@Name("trnPaymentOrder")
@Scope(ScopeType.SESSION)
public class TrnPaymentOrder {
	
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private String initVar;
	private Date today = null;

	// Task Attendees Attributes 
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In("#{comAssist}")
	private ComAssistant comAssist;
	@In Credentials credentials;
	@In Identity identity;
	private UsersBean user;
	
	// Attribute used for saving and deleting
	private EditNumbers numbers;
	private PaymentOrderHeadBean paymentOrderHead;
	private PaymentOrderDetBean paymentOrderDet;
	private TypeOfPayAndCollectionHeadBean typeOfPayAndCollectionHead;
	private TypeOfPayAndCollectionDetBean typeOfPayAndCollectionDet;
	private BankAccountsBean bankAccounts;
	private PaymentOrderDetBean paymentOrderDetData;
	private MethodOfPaymentBean methodOfPaymentData; 
	
    // Grilla de los comprobantes que vamos a estar afectando	
	private Collection<PaymentOrderDetBean> allPaymentOrderDet;
	
	private Collection<PaymentOrderDetBean> paymentOrderDetForLoad;
    //Grilla de las formas en que estaremos pagando al proveedor
	private Collection<MethodOfPaymentBean> allMethodOfPayment;
	// For Query of all Orders
	private PaymentOrderHeadBean paymentOrderAuthHead;
	private PaymentOrderDetBean paymentOrderAuthDet;
	private Collection<PaymentOrderHeadBean> allpaymentOrderAuthHead;
	private Collection<PaymentOrderDetBean> allpaymentOrderAuthDet;
	private PaymentOrderHeadBean paymentOrderQueryHead;
	private PaymentOrderDetBean paymentOrderQueryDet;
	private Collection<PaymentOrderHeadBean> allpaymentOrderQueryHead;
	private Collection<PaymentOrderDetBean> allpaymentOrderQueryDet;
	
	// Services
	private PurchasesServices prchSrv;
	private PaymentOrderServices poSrv;
	private MethodOfPaymentServices mOfPaySrv;
	private TypeOfPayAndCollectionServices topSrv;
	private BankAccountsServices baSrv;
	private UsersServices usSrv;
	private CurrencyServices crSrv;
	private QuotationServices qtSrv;
	private PaymentOrderHeadBean payOrHeadBean = new PaymentOrderHeadBean(); 
	
    private Long paymentOrderHeadNumber = new Long(0);
    
 // RichFaces dataScroller variables
	private modalSelectHolder selectHolder;
	private HtmlDatascroller scroller = new HtmlDatascroller();
	private Integer scrollerPage = new Integer(0);
	private Boolean selectedAll = false;
	
	
	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	/**
	 * This method is used for class initializing 
	 */
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.loadUserData();
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.initQueryObjects();
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	
	/**
	 * Retrieve the data of the logged user 
	 * and store the data into a user object
	 * 
	 * @return      is a void method, just store the data into an object
	 */
	private void loadUserData() throws CommonException{
		if(user == null){
		   user = new UsersBean();
		}
		if(usSrv == null){
		   usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		if(credentials != null){
			System.out.println("Credenciales Encontradas");
			this.getUser().setUserName(credentials.getUsername());
			System.out.println("User Name: " + this.getUser().getUserName());
			user = usSrv.getUserDataByName(this.getUser().getUserName());
			this.setUser(user);
			System.out.println("User: " + this.getUser());
		}else{	
			System.out.println("Credenciales Nulas");
		}
	}
	
	
	/**
	 * Initialize the entity Beans 
	 */
	public void initBeans(){
		
		
        if (paymentOrderHead == null){
        	paymentOrderHead = new PaymentOrderHeadBean();
        	paymentOrderHead.setIdEnt(user.getIdEnt());
        	paymentOrderHead.setIdBranch(user.getDefaultBranch());
        	paymentOrderHead.setStatus("PEND");
		}
		
		if (paymentOrderDet == null){
			paymentOrderDet = new PaymentOrderDetBean();
		}
		
		if (typeOfPayAndCollectionHead == null){
			typeOfPayAndCollectionHead = new TypeOfPayAndCollectionHeadBean();
		}
		
		if (typeOfPayAndCollectionDet == null){
			typeOfPayAndCollectionDet = new TypeOfPayAndCollectionDetBean();
		}
		
		if (bankAccounts == null){
			bankAccounts = new BankAccountsBean();
		}
		
		if (paymentOrderDetData == null){
			paymentOrderDetData = new PaymentOrderDetBean();
			paymentOrderDetData.setAmountOfPaymentOrden(new BigDecimal("0"));
		}
		if (methodOfPaymentData == null){
			methodOfPaymentData =  new MethodOfPaymentBean();
		}
			
	}
	
	/**
     * Initialize the services objects 
     */
    public void initServices() throws CommonException{
            
            if (prchSrv == null){
                prchSrv = new PurchasesServices(this.sqlMap.getConfig());
            }
            
            if (poSrv == null){
                poSrv = new PaymentOrderServices(this.sqlMap.getConfig());
            }
            
            if (mOfPaySrv == null){
                mOfPaySrv = new MethodOfPaymentServices(this.sqlMap.getConfig());
            }
            
            if (baSrv == null){
                baSrv = new BankAccountsServices(this.sqlMap.getConfig());
            }
            
            if (topSrv == null){
                topSrv = new TypeOfPayAndCollectionServices(this.sqlMap.getConfig());
            }
            
            if (crSrv == null) {
                crSrv = new CurrencyServices(this.sqlMap.getConfig());
            }
            
            if (qtSrv == null) {
                qtSrv = new QuotationServices(this.sqlMap.getConfig());
            }
                            
    }

	
	/**
	 * Initialize the Assistants objects 
	 */
	public void initAssistants(){
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(comAssist == null){
			comAssist = new ComAssistant();
		}
		if (numbers == null){
			numbers = new EditNumbers();
		}

	}
	
	/**
	 * Initialize collection objects 
	 */
	public void initCollections(){
		
		if(allPaymentOrderDet == null){
			allPaymentOrderDet = new ArrayList<PaymentOrderDetBean>();
		}
		
		if(paymentOrderDetForLoad == null){
			paymentOrderDetForLoad = new ArrayList<PaymentOrderDetBean>();
		}
		
		if(allMethodOfPayment == null){
			allMethodOfPayment = new ArrayList<MethodOfPaymentBean>();
		}

	}
	
	/**
	 * Clean all objects
	 */
	public void cleanData(){

		paymentOrderHead = null;
		paymentOrderDet = null;
		typeOfPayAndCollectionHead = null;
		typeOfPayAndCollectionDet = null;

		bankAccounts = null;
		paymentOrderDetData = null;
		methodOfPaymentData = null;
		
		// Collections
		allPaymentOrderDet = null;
		paymentOrderDetForLoad = null;
	    allMethodOfPayment = null;
		
		// Services
		prchSrv = null;
		poSrv = null;
		baSrv = null;
		topSrv = null;
		usSrv = null;
		crSrv = null;
		qtSrv = null;
		mOfPaySrv = null;
		
		numbers = null;
	}
	
	public void cleanAuth(){

		// First we clean
		paymentOrderAuthHead = new PaymentOrderHeadBean();
		paymentOrderAuthDet = new PaymentOrderDetBean();
		allpaymentOrderAuthHead = new ArrayList<PaymentOrderHeadBean>();
		allpaymentOrderAuthDet = new ArrayList<PaymentOrderDetBean>();
		
		// Then we initialize the objects
		this.initQueryObjects();
		
	}
	
	public void cleanQuery(){
		
		// First we clean
		paymentOrderQueryHead = new PaymentOrderHeadBean();
		paymentOrderQueryDet = new PaymentOrderDetBean();
		allpaymentOrderQueryHead = new ArrayList<PaymentOrderHeadBean>();
		allpaymentOrderQueryDet = new ArrayList<PaymentOrderDetBean>();
		
		// Then we initialize the objects
		this.initQueryObjects();
		
	}
	
	public void initQueryObjects() {

		if (paymentOrderAuthHead == null) {
			paymentOrderAuthHead = new PaymentOrderHeadBean();
		}

		if (paymentOrderAuthDet == null) {
			paymentOrderAuthDet = new PaymentOrderDetBean();
		}
		
		if(allpaymentOrderAuthHead == null){
			allpaymentOrderAuthHead = new ArrayList<PaymentOrderHeadBean>();
		}
		
		if(allpaymentOrderAuthDet == null){
			allpaymentOrderAuthDet = new ArrayList<PaymentOrderDetBean>();
		}
		if (paymentOrderQueryHead == null) {
			paymentOrderQueryHead = new PaymentOrderHeadBean();
		}

		if (paymentOrderQueryDet == null) {
			paymentOrderQueryDet = new PaymentOrderDetBean();
		}
		
		if(allpaymentOrderQueryHead == null){
			allpaymentOrderQueryHead = new ArrayList<PaymentOrderHeadBean>();
		}
		
		if(allpaymentOrderQueryDet == null){
			allpaymentOrderQueryDet = new ArrayList<PaymentOrderDetBean>();
		}
	}

	/**
     * Cancel Current operation and clean form objects.
     */
    public void cancelData() throws CommonException {
   //this.facesMessages.clear();
            this.setInitVar("S");
            this.cleanData();
            this.initData();
    }
    
    public Boolean activeVouchersQuery() {
            if (this.getPaymentOrderHead().getSupplierData() == null 
                    || this.getPaymentOrderHead().getSearchStartDate() == null
                    || this.getPaymentOrderHead().getSearchEndDate() == null) {
                    System.out.println("ENABLE VOUCHERS QUERY: FALSE");
                    return false;

            } else {
//                  System.out.println("SEARCH: SUPPLIER: "+this.getPaymentOrderHead().getSupplierData().getId());
//                  System.out.println("SEARCH: ENT: "+this.paymentOrderHead.getIdEnt());
//                  System.out.println("SEARCH: START DATE: "+this.paymentOrderHead.getSearchStartDate().toString());
//                  System.out.println("SEARCH: END DATE: "+this.paymentOrderHead.getSearchEndDate().toString());
                    if (aid.getFeesToSuppliersForPaymentList(
                                    this.paymentOrderHead.getIdEnt(), 
                                    this.paymentOrderHead.getSupplierData().getId(), 
                                    this.paymentOrderHead.getSearchStartDate(), 
                                    this.paymentOrderHead.getSearchEndDate()).isEmpty()){
                            
                            System.out.println("ENABLE VOUCHERS QUERY: FALSE");
                            
                            comAssist.generateErrorMsg(
                                            "No se encontraron Comprobantes para los parametros ingresados", 
                                            "actionForm:payOrderSearchVouchersBtn");
                            
                            return false;
                    } else {
                            System.out.println("activeVouchersQuery RENDER ORDER QUERY: TRUE");
                            return true;
                    }
            }

    }
    
    public void retrieveChangeType() throws ParseException, CommonException {
            System.out.println("RETRIEVING CHANGE TYPE");
            // First we verify for null object
            if (this.getPaymentOrderHead().getCurrencyData() == null) {
                    System.out.println("Currency Data is NULL");
            } else {
                    // If object is not null
                    // We retrieve the parameters
                    Long localCurrency = this.crSrv.getIdCurrency("GUAR");
                    Long idCurrency = this.getPaymentOrderHead().getCurrencyData().getId();
                    if (idCurrency.equals(localCurrency)) {
                            this.getPaymentOrderHead().setChangeType(new Double(1));
                    } else {
                            Date startDate = DateAssistant.getCurrentDate();
                            System.out.println(" ##### CHANGE TYPE DATE: ".concat(startDate.toString()).concat(" ##### "));
                            System.out.println(" ##### currency id = ".concat(idCurrency.toString()).concat(" ##### "));
                            // Then we retrieve the changeType based on passed parameters
                            Double changeType = (Double) this.qtSrv.getAmountQuotation(idCurrency, startDate);

                            // And set the changeType value
                            if (changeType == null) {
                                    FacesMessages.instance().add("La moneda seleccionada no tiene cotizaci�n para la fecha. Favor inserte la cotizaci�n");
                                    this.getPaymentOrderHead().setChangeType(new Double(0));
                            } else {
                                    this.getPaymentOrderHead().setChangeType(changeType);
                                    System.out.println("CHANGE TYPE: " + (this.getPaymentOrderHead().getChangeType()));
                            }
                    }
            }
    }
    public Double retrieveChangeTypeByIdCurrencyDate(Long pIdCurrency, Date pDate) throws ParseException, CommonException {
            Double vChangeType = new Double (0);
            Long localCurrency = this.crSrv.getIdCurrency("GUAR");

            if (pIdCurrency.equals(localCurrency)) {
                    vChangeType = new Double(1);
            } else {
                    Date startDate = DateAssistant.getCurrentDate();
                    System.out.println(" ##### CHANGE TYPE DATE: ".concat(pDate.toString()).concat(" ##### "));
                    System.out.println(" ##### currency id = ".concat(pIdCurrency.toString()).concat(" ##### "));
                    // Then we retrieve the changeType based on passed parameters
                vChangeType = (Double) this.qtSrv.getAmountQuotation(pIdCurrency, pDate);
            }
            return vChangeType;
    }

    public void retrieveVouchersForLoad() {
            try {
                    
                    this.setPaymentOrderDetForLoad(
                                    this.prchSrv.getFeesToSuppliersForPayment(
                                                    this.getPaymentOrderHead().getIdEnt(), 
                                                    this.getPaymentOrderHead().getSupplierData().getId(), 
                                                    this.getPaymentOrderHead().getSearchStartDate(), 
                                                    this.getPaymentOrderHead().getSearchEndDate())
                            );

            } catch (Exception e) {
                    System.out.println("NO SE PUDO INSERTAR LA GRILLA DE COMPROBANTES " + e.getMessage());
            }
    }
    
    public Boolean enableIfRowSelected(Boolean selected){
            if(selected.equals(true)){
                    return false;
            }else{
                    return true;
            }
    }
    public void loadGridVouchers() {
            try {
            	if(this.paymentOrderDetForLoad.isEmpty()){
            		this.comAssist.generateErrorMsg(
							"Favor seleccione al menos un comprobante", 
							"actionform:payOrderLoadVouchersBtn");
            	}else{
            		Boolean valid = this.validateInstalments();
                	if(valid == true){
                		Double totalPayment = new Double(0);
                        System.out.println("Loading Vouchers");
                        Iterator<PaymentOrderDetBean> it1 = paymentOrderDetForLoad.iterator();
                        while(it1.hasNext()){
                                PaymentOrderDetBean next = it1.next();
                                if(next.getSelected().equals(true)){
                                        this.allPaymentOrderDet.add(next);
                                        totalPayment += next.getAmountOfPaymentOrden().doubleValue();
                                        System.out.println("Payment: "+next.getAmountOfPaymentOrden().toString());
                                }
                        }
                        Double totalPaymentRounded = ComAssistant.round(totalPayment, 5);
                        this.getPaymentOrderHead().setTotalPaymentOrder(new BigDecimal(Double.toString(totalPaymentRounded)));
                	}else{
                		return;
                	}
            	}
                
            } catch (Exception e) {
                System.out.println("NO SE PUDO INSERTAR LA GRILLA DE COMPROBANTES " + e.getMessage());
            }
    }
    
    public void clearGridVouchers(){
            Iterator<PaymentOrderDetBean> paymentOrDet = this.allPaymentOrderDet.iterator();
            while (paymentOrDet.hasNext()) {
                    PaymentOrderDetBean next = (PaymentOrderDetBean)paymentOrDet.next();
                    if (next.getSelected().equals(true)){
                            paymentOrDet.remove();
                    }
            }
    }
    
    public void loadGridMethodOfPayment(){
            try {
                    Double totalMethodOfPayment = new Double(0);
                    if (this.methodOfPaymentData == null){
                            System.out.println("En loadGridMethodOfPayment this.methodOfPaymentData == null");
                    }else{
                            this.methodOfPaymentData.setAmount(this.getPaymentOrderHead().getTotalPaymentOrder());
                            this.methodOfPaymentData.setIdCurrency(this.getMethodOfPaymentData().getBankAccountsData().getIdCurrency());
                            this.methodOfPaymentData.setIdBankAccounts(this.getMethodOfPaymentData().getBankAccountsData().getId());
                            this.methodOfPaymentData.setIdEnt(this.getMethodOfPaymentData().getBankAccountsData().getIdEnt());
                            this.methodOfPaymentData.setPayee(convert.getSupplierName(this.getPaymentOrderHead().getSupplierData().getId()));
                            this.allMethodOfPayment.add(this.methodOfPaymentData);
                            
                            Iterator<MethodOfPaymentBean> it = this.allMethodOfPayment.iterator();
                            
                            while(it.hasNext()){
                                    MethodOfPaymentBean next = it.next();
                                    totalMethodOfPayment += next.getAmount().doubleValue();
                            }
                            Double totalMethodOfPaymentRounded = ComAssistant.round(totalMethodOfPayment, 5);
                            this.getPaymentOrderHead().setTotalMethodOfPayment(new BigDecimal(Double.toString(totalMethodOfPaymentRounded)));
                            
                    }
            } catch (Exception e) {
                    System.out.println("NO SE PUDO INSERTAR LA GRILLA DE FORMAS DE PAGO " + e.getMessage());
            }
    }
    
    public void clearGridMethodOfPayment(){
            Iterator<MethodOfPaymentBean> metOfPayment = this.allMethodOfPayment.iterator();
            while (metOfPayment.hasNext()) {
                    MethodOfPaymentBean next = (MethodOfPaymentBean)metOfPayment.next();
                    if (next.getSelected().equals(true)){
                            metOfPayment.remove();
                    }
            }
    }
    
    public void savePaymentOrderHead() throws CommonException {
            this.setPaymentOrderHeadNumber(new Long(0));
            
            PaymentOrderHeadBean newPaymentOrderHead = new PaymentOrderHeadBean();
            
            if(this.getPaymentOrderHead() == null){
                    System.out.println("this.getPaymentOrderHead() == null");
            }else{                          
                    newPaymentOrderHead.setIdEnt(user.getIdEnt());
                    newPaymentOrderHead.setIdBranch(user.getDefaultBranch());
                    this.numbers.setInitVar("S");
                    this.numbers.initData();
                    newPaymentOrderHead.setVoucher(this.numbers.getNumber(newPaymentOrderHead.getIdEnt(), "ORDPA"));
                    newPaymentOrderHead.setIdProv(this.getPaymentOrderHead().getSupplierData().getId());
                    newPaymentOrderHead.setVoucherDate(this.getPaymentOrderHead().getVoucherDate());
                    newPaymentOrderHead.setIdCurrency(this.getPaymentOrderHead().getCurrencyData().getId());
                    newPaymentOrderHead.setChangeType(this.getPaymentOrderHead().getChangeType());
                    newPaymentOrderHead.setStatus(this.getPaymentOrderHead().getStatus());
                    newPaymentOrderHead.setIdCancellationReason(null);
                    newPaymentOrderHead.setTotalPaymentOrder(this.getPaymentOrderHead().getTotalPaymentOrder());
                    newPaymentOrderHead.setTotalMethodOfPayment(this.getPaymentOrderHead().getTotalMethodOfPayment());
                    
                    this.poSrv.saveNewPaymentOrderHead(newPaymentOrderHead);
                    
                    /* Para recuperar el id de la transaccion */
                    this.setPaymentOrderHeadNumber(newPaymentOrderHead.getVoucher());
            }
    }
    
    public void savePaymentOrderDet() throws CommonException, ParseException{
            PaymentOrderDetBean newPaymentOrderDet = new PaymentOrderDetBean();
            PurchasesHeadBean newPurchaseHead = new PurchasesHeadBean();
            if(this.getPaymentOrderDet() == null){
                    System.out.println("this.getPaymentOrderDet() == null");
            }else{
                    
                    PaymentOrderServices poCabSrv = new PaymentOrderServices(this.sqlMap.getConfig());
                    payOrHeadBean = poCabSrv.getPaymentOrderHeadByEntVoucher(user.getIdEnt(), this.getPaymentOrderHeadNumber());
                    if (payOrHeadBean == null) {
                            System.out.println("no se encontro en registro de cabecera para continuar la transaccion ");
                    }
                    
                    // SAVING DETAIL
                    Integer vContador = new Integer(0);
                    for (PaymentOrderDetBean paymentDet:  allPaymentOrderDet) {
                            vContador++;

                            // Processing Tax
                            // this.comAssist.processTax(this.getPurchasesDet().getTaxData(),
                            // this.getPurchasesDet().getItemTotal());
                            System.out.println("###### vContador  #####".concat(vContador.toString()));

                            // Setting Fields
                            newPaymentOrderDet.setIdHead(payOrHeadBean.getId());
                            newPaymentOrderDet.setItem(new Long(vContador));
                            newPaymentOrderDet.setIdTransRef(paymentDet.getIdTransRef());
                            newPaymentOrderDet.setIdTypeTransRef(paymentDet.getIdTypeTransRef());
                            newPaymentOrderDet.setStatus("PEND");
                            newPaymentOrderDet.setStatusDate(DateAssistant.getHoleDateTime());
                            newPaymentOrderDet.setUserIns(this.user.getIdEnt());
                            newPaymentOrderDet.setInstalments(paymentDet.getInstalments());
                            newPaymentOrderDet.setAmountOfPaymentOrden(paymentDet.getAmountOfPaymentOrden());
                            
                            this.poSrv.saveNewPaymentOrderDet(newPaymentOrderDet);
                    }
            }
    }
    
    public void saveMethodOfPayment() throws CommonException, ParseException{
            MethodOfPaymentBean newMethodOfPayment = new MethodOfPaymentBean();
            
            if(this.getMethodOfPaymentData() == null){
                    System.out.println("this.getMethodOfPaymentData() == null");
            }else{       
               VoucherBean vouBean = new VoucherBean();
               VoucherServices vouSrv = new VoucherServices(this.sqlMap.getConfig());
               vouBean = vouSrv.getVoucherBeanByShortName("ORDPA");
               
               Iterator<MethodOfPaymentBean> it = this.allMethodOfPayment.iterator();
               Long vContador = new Long (0);
               while(it.hasNext()){
                       vContador += 1;
                       MethodOfPaymentBean next = it.next();
                       newMethodOfPayment.setIdEnt(user.getIdEnt());
                       newMethodOfPayment.setIdTransRef(this.payOrHeadBean.getId());
                       newMethodOfPayment.setIdTypeTransRef(vouBean.getId());
                       newMethodOfPayment.setIdMovementCashbox(next.getIdMovementCashbox());
                       newMethodOfPayment.setItem(vContador);
                       newMethodOfPayment.setInsDateTime(DateAssistant.getHoleDateTime());
                       newMethodOfPayment.setInsDate(DateAssistant.getCurrentDate());
                       newMethodOfPayment.setIdCurrency(next.getIdCurrency());
                       newMethodOfPayment.setChangeType(retrieveChangeTypeByIdCurrencyDate(next.getIdCurrency(), DateAssistant.getCurrentDate()));
                       if (newMethodOfPayment.getChangeType() == null) {
                               System.out.println("** tipo de cambio nulo en formas de pago para la cuenta bancaria " + next.getIdBankAccounts());
                       }
                       newMethodOfPayment.setIdTypePay(next.getIdTypePay());
                       newMethodOfPayment.setIdBankAccounts(next.getIdBankAccounts());
                       newMethodOfPayment.setIdCard(next.getIdCard());
                       newMethodOfPayment.setNumValue(next.getNumValue());
                       newMethodOfPayment.setBroadcastDate(DateAssistant.getCurrentDate());
                       newMethodOfPayment.setExpirationDate(DateAssistant.getHoleDateTime());
                       newMethodOfPayment.setPayee(next.getPayee());
                       newMethodOfPayment.setAmount(next.getAmount());
                       newMethodOfPayment.setUserIns(user.getId());
                       newMethodOfPayment.setDateIns(DateAssistant.getHoleDateTime());
                       
                       this.mOfPaySrv.saveNewMethodOfPayment(newMethodOfPayment);
               }
            }
    }
    
    public void saveNewData(){
            try {
			// Boolean validateTotal =
			// this.comAssist.validatePaymentOrderTotal(this.paymentOrderHead.getTotalPaymentOrder(),
			// this.paymentOrderHead.getTotalMethodOfPayment());
			//                  
			if (!true) {
				System.out.println("los totales no coinciden :( ");
				return;
			} else {
				try {
					System.out.println("antes de grabar la cabecera savePaymentOrderHead()");
					savePaymentOrderHead();
					System.out.println("antes de grabar comprobantes savePaymentOrderDet()");
					savePaymentOrderDet();
					saveMethodOfPayment();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					System.out
							.println("NO SE PUDO savePaymentOrderHead- savePaymentOrderDet. "
									+ e.getMessage());
					e.printStackTrace();
				}
				System.out
						.println("antes de grabar formas de pago saveMethodOfPayment()");
			}

		} catch (CommonException e) {
			// TODO: handle exception
			// this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());

			log.error(e);
		} finally {
			this.cleanData(); // Cleaning Objects
			this.setInitVar("S"); // Setting initialization Flag
		}
    }

    public void resetAmount(PaymentOrderDetBean object, Boolean selected){
    	System.out.println("RESETING VALUE");
    	if(selected == true){
    		object.setAmountOfPaymentOrden(new BigDecimal("0"));
    	}else{
    		object.setAmountOfPaymentOrden(null);
    	}
		
    	
    }
	public Boolean validateInstalments(){
		Boolean valid = true;
		String voucher = new String();
		BigDecimal lastResidue = new BigDecimal("0");
		BigDecimal lastAmount = new BigDecimal("0");
		Iterator<PaymentOrderDetBean> it1 = paymentOrderDetForLoad.iterator();
        while(it1.hasNext()){
        	PaymentOrderDetBean next = it1.next();
        	System.out.println("VALIDAR CUOTAS - CUOTAS: "+next.getInstalments());
        	System.out.println("VALIDAR CUOTAS - VOUCHER: "+next.getVoucher());
        	System.out.println("VALIDAR CUOTAS - PAGO: "+next.getAmountOfPaymentOrden());
        	System.out.println("VALIDAR CUOTAS - RESIDUE: "+next.getResiduePaymentOrden());
        	System.out.println("VALIDAR CUOTAS - ULTIMO MONTO: "+lastAmount);
    		if(next.getInstalments() == 1){
    			System.out.println("CUOTA IGUAL A 1");
        		voucher = next.getVoucher();
        		if(next.getAmountOfPaymentOrden() != null){
        			lastAmount = next.getAmountOfPaymentOrden();
        			lastResidue = next.getResiduePaymentOrden().subtract( next.getAmountOfPaymentOrden());
        		}
//        		if(next.getAmountOfPaymentOrden() == null){
//        			lastAmount = new BigDecimal("0");
//        			lastResidue = next.getResiduePaymentOrden();
//        		}
        	}
    		if(next.getInstalments() > 1){
    			System.out.println("CUOTA MAYOR A 1");
    			if(next.getVoucher().equals(voucher)){
    				System.out.println("SAME VOUCHER");
        			if(next.getAmountOfPaymentOrden() != null){
        				System.out.println("LAST RESIDUE: "+lastResidue);
        				if(lastAmount.equals(new BigDecimal("0")) || lastAmount.equals(null)){
        					System.out.println("ULTIMO MONTO IGUAL A 0");
        					this.comAssist.generateErrorMsg(
        							"El pago de las cuotas debe realizarse de forma consecutiva", 
        							"actionform:payOrderLoadVouchersBtn");
        					valid = false;
        					break;
        				}else{
        					if(lastResidue.doubleValue() > new BigDecimal("0").doubleValue()){
        						System.out.println("ULTIMO MONTO IGUAL A 0");
            					this.comAssist.generateErrorMsg(
            							"El pago de las cuotas debe realizarse de forma consecutiva", 
            							"actionform:payOrderLoadVouchersBtn");
            					valid = false;
            					break;
        					}else{
        						lastAmount = next.getAmountOfPaymentOrden();
        						lastResidue = next.getResiduePaymentOrden().subtract( next.getAmountOfPaymentOrden());
        					}
        					
        				}
        			}
        		}
        	}	
        }
        return valid;
	}
	
	public void retrievePendingPaymentOrders(PaymentOrderHeadBean poHeadp) throws SQLException {
		try {
			Long idSupplier = null;
			Date voucherDate = null;
			String status = new String("PEND");
			if (poHeadp.getSupplierData() != null) {
				idSupplier = poHeadp.getSupplierData().getId();
			}

			if (poHeadp.getVoucherDate() != null) {
				voucherDate = poHeadp.getVoucherDate();
			}
			
			this.setAllpaymentOrderAuthHead(poSrv.getPendingPaymentOrders(idSupplier, voucherDate, status));
			System.out.println("PENDING PURCHASES LIST CONFIRM: "
					+ this.allpaymentOrderAuthHead);
			if(this.allpaymentOrderAuthHead.isEmpty()){
				this.comAssist.generateInfoMsg("No Existen Ordenes de pago con estado Pendiente", "actionform:pAuthSearchBtn");
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}

	}
	
	public void retrievesPaymentOrders(PaymentOrderHeadBean poHeadp) throws SQLException {
		try {
			Long idSupplier = null;
			Date startDate = null;
			Date endDate = null;
			String status = null;
			
			if (poHeadp.getSupplierData() != null) {
				idSupplier = poHeadp.getSupplierData().getId();
			}
			
			if (poHeadp.getStatus() != null) {
				status = poHeadp.getStatus();
			}

			if (poHeadp.getVoucherDate() != null) {
				startDate = poHeadp.getSearchStartDate();
			}
			
			if (poHeadp.getVoucherDate() != null) {
				startDate = poHeadp.getSearchEndDate();
			}
			
			this.setAllpaymentOrderQueryHead(poSrv.getPaymentOrders(idSupplier, startDate, endDate, status));
			System.out.println("PAYMENT ORDERS LIST CONFIRM: " + this.allpaymentOrderQueryHead);
			if(this.allpaymentOrderQueryHead.isEmpty()){
				this.comAssist.generateInfoMsg("No se encontraron Ordenes de pago", "actionform:pPayOrderQuerySearchBtn");
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}

	}
	
	public void retrievePaymentOrderDet(Long idHead){
		
		try{
			this.setAllpaymentOrderQueryDet(poSrv.getPaymentOrderDetByHeadId(idHead));
			System.out.println("QUERY ORDER DET: " + this.allpaymentOrderAuthDet);
			
		}catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR setAllpaymentOrderQueryDet. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void confirmPaymentOrder() throws SQLException{
		try{
			Boolean noneSelected = true;
			Iterator<PaymentOrderHeadBean> it = allpaymentOrderAuthHead.iterator();
			
			while(it.hasNext()){
				PaymentOrderHeadBean next = it.next();
				if(next.getSelected() == true){
					noneSelected = false;
					this.poSrv.confirmPaymentOrder(next.getId());
				}
				if(!it.hasNext()){
					this.comAssist.generateInfoMsg(
							"Comfirmaci�n realizada con �xito!",
							"actionform:payAuthBtn");
				}
			}
			
			if(noneSelected == true){
				this.comAssist.generateErrorMsg("Favor seleccione al menos un registro", "actionform:payAuthBtn");
			}else{
				this.retrievePendingPaymentOrders(this.getPaymentOrderAuthHead());
			}

			
		}catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			
			log.error(e);
		}
		
	}
	
	public void cancelPaymentOrder() throws SQLException{
		try{
			Boolean noneSelected = true;
			Iterator<PaymentOrderHeadBean> it = allpaymentOrderAuthHead.iterator();
			
			while(it.hasNext()){
				PaymentOrderHeadBean next = it.next();
				if(next.getSelected() == true){
					noneSelected = false;
					this.poSrv.cancelPaymentOrder(next.getId());
				}
				if(!it.hasNext()){
					this.comAssist.generateInfoMsg(
							"Anulaci�n realizada con �xito!",
							"actionform:payCancelBtn");
				}
			}
			
			if(noneSelected == true){
				this.comAssist.generateErrorMsg("Favor seleccione al menos un registro", "actionform:payCancelBtn");
			}else{
				this.retrievePendingPaymentOrders(this.getPaymentOrderAuthHead());
			}

			
		}catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			
			log.error(e);
		}
		
	}


	public FacesMessages getFacesMessages() {
		return facesMessages;
	}


	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}


	public Log getLog() {
		return log;
	}


	public void setLog(Log log) {
		this.log = log;
	}


	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}


	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}


	public String getInitVar() {
		return initVar;
	}


	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}


	public UsersBean getUser() {
		return user;
	}


	public void setUser(UsersBean user) {
		this.user = user;
	}


	public PaymentOrderHeadBean getPaymentOrderHead() {
		return paymentOrderHead;
	}


	public void setPaymentOrderHead(PaymentOrderHeadBean paymentOrderHead) {
		this.paymentOrderHead = paymentOrderHead;
	}


	public PaymentOrderDetBean getPaymentOrderDet() {
		return paymentOrderDet;
	}


	public void setPaymentOrderDet(PaymentOrderDetBean paymentOrderDet) {
		this.paymentOrderDet = paymentOrderDet;
	}


	public TypeOfPayAndCollectionHeadBean getTypeOfPayAndCollectionHead() {
		return typeOfPayAndCollectionHead;
	}


	public void setTypeOfPayAndCollectionHead(
			TypeOfPayAndCollectionHeadBean typeOfPayAndCollectionHead) {
		this.typeOfPayAndCollectionHead = typeOfPayAndCollectionHead;
	}


	public TypeOfPayAndCollectionDetBean getTypeOfPayAndCollectionDet() {
		return typeOfPayAndCollectionDet;
	}


	public void setTypeOfPayAndCollectionDet(
			TypeOfPayAndCollectionDetBean typeOfPayAndCollectionDet) {
		this.typeOfPayAndCollectionDet = typeOfPayAndCollectionDet;
	}


	public BankAccountsBean getBankAccounts() {
		return bankAccounts;
	}


	public void setBankAccounts(BankAccountsBean bankAccounts) {
		this.bankAccounts = bankAccounts;
	}

	public MethodOfPaymentBean getMethodOfPaymentData() {
		return methodOfPaymentData;
	}


	public void setMethodOfPaymentData(MethodOfPaymentBean methodOfPaymentData) {
		this.methodOfPaymentData = methodOfPaymentData;
	}


	public Collection<MethodOfPaymentBean> getAllMethodOfPayment() {
		return allMethodOfPayment;
	}


	public void setAllMethodOfPayment(
			Collection<MethodOfPaymentBean> allMethodOfPayment) {
		this.allMethodOfPayment = allMethodOfPayment;
	}


	public EditNumbers getNumbers() {
		return numbers;
	}


	public void setNumbers(EditNumbers numbers) {
		this.numbers = numbers;
	}


	public Long getPaymentOrderHeadNumber() {
		return paymentOrderHeadNumber;
	}


	public void setPaymentOrderHeadNumber(Long paymentOrderHeadNumber) {
		this.paymentOrderHeadNumber = paymentOrderHeadNumber;
	}


	public PaymentOrderDetBean getPaymentOrderDetData() {
		return paymentOrderDetData;
	}


	public void setPaymentOrderDetData(PaymentOrderDetBean paymentOrderDetData) {
		this.paymentOrderDetData = paymentOrderDetData;
	}


	public Collection<PaymentOrderDetBean> getAllPaymentOrderDet() {
		return allPaymentOrderDet;
	}


	public void setAllPaymentOrderDet(
			Collection<PaymentOrderDetBean> allPaymentOrderDet) {
		this.allPaymentOrderDet = allPaymentOrderDet;
	}


	public Collection<PaymentOrderDetBean> getPaymentOrderDetForLoad() {
		return paymentOrderDetForLoad;
	}


	public void setPaymentOrderDetForLoad(
			Collection<PaymentOrderDetBean> paymentOrderDetForLoad) {
		this.paymentOrderDetForLoad = paymentOrderDetForLoad;
	}


	public modalSelectHolder getSelectHolder() {
		return selectHolder;
	}


	public void setSelectHolder(modalSelectHolder selectHolder) {
		this.selectHolder = selectHolder;
	}


	public HtmlDatascroller getScroller() {
		return scroller;
	}


	public void setScroller(HtmlDatascroller scroller) {
		this.scroller = scroller;
	}


	public Integer getScrollerPage() {
		return scrollerPage;
	}


	public void setScrollerPage(Integer scrollerPage) {
		this.scrollerPage = scrollerPage;
	}


	public Boolean getSelectedAll() {
		return selectedAll;
	}


	public void setSelectedAll(Boolean selectedAll) {
		this.selectedAll = selectedAll;
	}


	public PaymentOrderHeadBean getPaymentOrderAuthHead() {
		return paymentOrderAuthHead;
	}


	public void setPaymentOrderAuthHead(PaymentOrderHeadBean paymentOrderAuthHead) {
		this.paymentOrderAuthHead = paymentOrderAuthHead;
	}


	public PaymentOrderDetBean getPaymentOrderAuthDet() {
		return paymentOrderAuthDet;
	}


	public void setPaymentOrderAuthDet(PaymentOrderDetBean paymentOrderAuthDet) {
		this.paymentOrderAuthDet = paymentOrderAuthDet;
	}


	public Collection<PaymentOrderHeadBean> getAllpaymentOrderAuthHead() {
		return allpaymentOrderAuthHead;
	}


	public void setAllpaymentOrderAuthHead(
			Collection<PaymentOrderHeadBean> allpaymentOrderAuthHead) {
		this.allpaymentOrderAuthHead = allpaymentOrderAuthHead;
	}


	public Collection<PaymentOrderDetBean> getAllpaymentOrderAuthDet() {
		return allpaymentOrderAuthDet;
	}


	public void setAllpaymentOrderAuthDet(
			Collection<PaymentOrderDetBean> allpaymentOrderAuthDet) {
		this.allpaymentOrderAuthDet = allpaymentOrderAuthDet;
	}


	public PaymentOrderHeadBean getPaymentOrderQueryHead() {
		return paymentOrderQueryHead;
	}


	public void setPaymentOrderQueryHead(PaymentOrderHeadBean paymentOrderQueryHead) {
		this.paymentOrderQueryHead = paymentOrderQueryHead;
	}


	public PaymentOrderDetBean getPaymentOrderQueryDet() {
		return paymentOrderQueryDet;
	}


	public void setPaymentOrderQueryDet(PaymentOrderDetBean paymentOrderQueryDet) {
		this.paymentOrderQueryDet = paymentOrderQueryDet;
	}


	public Collection<PaymentOrderHeadBean> getAllpaymentOrderQueryHead() {
		return allpaymentOrderQueryHead;
	}


	public void setAllpaymentOrderQueryHead(
			Collection<PaymentOrderHeadBean> allpaymentOrderQueryHead) {
		this.allpaymentOrderQueryHead = allpaymentOrderQueryHead;
	}


	public Collection<PaymentOrderDetBean> getAllpaymentOrderQueryDet() {
		return allpaymentOrderQueryDet;
	}


	public void setAllpaymentOrderQueryDet(
			Collection<PaymentOrderDetBean> allpaymentOrderQueryDet) {
		this.allpaymentOrderQueryDet = allpaymentOrderQueryDet;
	}
	
	
}
